package com.atguigu.tingshu.order.context;


import com.atguigu.tingshu.order.strategy.SaveOrderStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SaveOrderStrategyContext implements ApplicationContextAware {

    // 管理SaveOrderStrategy接口的实现类对象
    private static final Map<String , SaveOrderStrategy> SAVE_ORDER_STRATEGY_MAP = new ConcurrentHashMap<String , SaveOrderStrategy>();


    // 根据支付方式选择保存订单的策略实现类对象
    public static SaveOrderStrategy getSaveOrderStrategy(String payWay) {
        return SAVE_ORDER_STRATEGY_MAP.get(payWay) ;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeansOfType(SaveOrderStrategy.class).values().forEach(saveOrderStrategy -> {
            String payWay = saveOrderStrategy.getPayWay();
            SAVE_ORDER_STRATEGY_MAP.put(payWay , saveOrderStrategy) ;
        }) ;
    }

}

